package com.example.chmextractor.service;

import org.jchmlib.ChmFile;
import org.jchmlib.ChmUnitInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.FileSystemException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChmExtractorService {
    
    public String extractToText(MultipartFile chmFile) throws IOException {
        // 创建临时文件来保存上传的CHM文件
        Path tempChmFile = Files.createTempFile("upload_", ".chm");
        chmFile.transferTo(tempChmFile.toFile());
        
        // 创建临时文件来保存输出的文本
        Path tempOutputFile = Files.createTempFile("output_", ".txt");
        
        try {
            ChmFile chm = new ChmFile(tempChmFile.toString());
            
            System.out.println("CHM文件编码：" + chm.getEncoding());
            System.out.println("CHM文件标题：" + chm.getTitle());
            
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(
                        new FileOutputStream(tempOutputFile.toFile()), 
                        StandardCharsets.UTF_8))) {
                
                List<ChmUnitInfo> htmlFiles = new ArrayList<>();
                
                // 使用enumerate方法遍历所有文件
                chm.enumerate(ChmFile.CHM_ENUMERATE_ALL, (ui) -> {
                    if (ui.getPath().toLowerCase().endsWith(".htm") || 
                        ui.getPath().toLowerCase().endsWith(".html")) {
                        htmlFiles.add(ui);
                    }
                });

                System.out.println("找到 " + htmlFiles.size() + " 个HTML文件");
                
                // 处理每个HTML文件
                for (ChmUnitInfo ui : htmlFiles) {
                    try {
                        String content = chm.retrieveObjectAsString(ui);
                        if (content != null) {
                            // 使用Jsoup解析HTML并提取文本
                            Document doc = Jsoup.parse(content);
                            String text = doc.text();
                            
                            // 获取文件的标题（如果有的话）
                            String title = chm.getTitleOfObject(ui.getPath());
                            
                            // 写入文件名和标题
                            writer.write("=== " + ui.getPath() + " ===\n");
                            if (!ui.getPath().equals(title)) {
                                writer.write("标题: " + title + "\n");
                            }
                            writer.write(text);
                            writer.write("\n\n");
                            
                            System.out.println("已处理: " + ui.getPath());
                        }
                    } catch (Exception e) {
                        System.err.println("处理文件 " + ui.getPath() + " 时出错: " + e.getMessage());
                    }
                }
            }
            
            // 读取生成的文本文件内容
            String content = new String(Files.readAllBytes(tempOutputFile), StandardCharsets.UTF_8);
            return content;
            
        } finally {
            
            // 清理临时文件
            // deleteFileWithRetry(tempChmFile);
            // deleteFileWithRetry(tempOutputFile);
        }
    }
    
    private void deleteFileWithRetry(Path path) throws IOException {
        int attempts = 5;
        while (attempts > 0) {
            try {
                Files.deleteIfExists(path);
                return;
            } catch (FileSystemException e) {
                attempts--;
                if (attempts == 0) {
                    throw e;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new IOException("Thread was interrupted", ie);
                }
            }
        }
    }
}
